<template>
  <el-select v-bind="$attrs" @focus="selectFocus" remote-show-suffix :remote-method="remoteMethod">
    <el-option
      v-for="dict in optionsList"
      :key="dict.value"
      :label="dict.label"
      :value="dict.value"
    />
    <template #footer>
      <div style="text-align: center">
        <el-button
          :loading="isLoading"
          type="primary"
          text
          @click="loadMore"
          :disabled="isLastPage || isLoading"
          >{{ isLoading ? '加载中' : isLastPage ? '已经加载全部' : '加载更多' }}</el-button
        >
      </div>
    </template>
  </el-select>
</template>

<script setup lang="ts">
interface Item {
  value: number | string,
  label: string | undefined
}

defineOptions({ name: 'ScorllSelect' })

const props = defineProps<{
  methods?: (param: any) => Promise<{
    list: []
    total: number
  }>
  searchKey: string
  preMap?: [],
}>()

const optionsList = ref<Item[]>([])

const queryFrom = ref({
  pageNo: 1,
  pageSize: 2,
  [props.searchKey]: ''
  // total: undefined,
})

/**
 * 1.首次加载数据 组件focus事件
 */
const isInit = ref(true)
const selectFocus = async (el) => {
  if (!isInit.value) return
  console.log(el)
  isInit.value = false
  optionsList.value = []
  queryFrom.value.pageNo = 1
  const res = await getList()
  optionsList.value = res.list
}

/**
 * 2.加载更多
 */
const loadMore = async () => {
  queryFrom.value.pageNo++
  const res = await getList()
  optionsList.value = [...optionsList.value, ...res.list]
}

/**
 * 3. 远程搜索
 */
const remoteMethod = async (queryKey: string) => {
  if(queryKey === '') return
  console.log(queryKey)
  optionsList.value = []
  queryFrom.value.pageNo = 1
  queryFrom.value[props.searchKey] = queryKey
  const res = await getList()
  optionsList.value = res.list
}

/**
 * 请求数据选项, 带分页和查询条件
 */
const isLoading = ref(false)
type TRes = { total: number; list: Item[] }
const getList = async () => {
  if (!props.methods) {
    return await new Promise<TRes>((resolve) => {
      resolve({ list: [], total: 0 })
    })
  }

  isLoading.value = true
  try {
    const res: TRes = await props.methods(queryFrom.value)
    judgeIsLastPage(res.total)
    return res
  } catch (error) {
    console.log(error)
    return { list: [] }
  } finally {
    isLoading.value = false
  }
}

/**
 * 判断是否为最后一页
 */
const isLastPage = ref(false)
function judgeIsLastPage(total) {
  const pageNo = queryFrom.value.pageNo
  const pageSize = queryFrom.value.pageSize
  const totalPages = Math.ceil(total / pageSize)
  isLastPage.value = pageNo >= totalPages
}

/**
 * 监听 编辑时的自动回显数据
 */
watch(
  () => props.preMap,
  (newVal) => {
    // if (newVal === undefined || newVal.value === undefined || newVal.value === '') return
    // optionsList.value.unshift(newVal)
    if (newVal === undefined || newVal.length === 0) return
    optionsList.value.unshift(...newVal)
  },
  { deep: true, once: true }
)
</script>

<style scoped></style>
